package com.cmw.kafka.demo1.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

@Slf4j
public class ProducerSample {
    private static final String TOPIC_NAME = "test-topic";

    public static void main(String[] args) {
        //通过 Producer 发送消息
        log.info("通过 Producer的 TOPIC:{} 发送消息", TOPIC_NAME);
        producerSend();
        log.info("往{}发送消息完成...",TOPIC_NAME);
    }

    public static void producerSend(){
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "114.67.85.67:9092");
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.RETRIES_CONFIG, "0");
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384");
        props.put(ProducerConfig.LINGER_MS_CONFIG, "1");
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //Producer 消息生产者对象
        Producer<String, String> producer = new KafkaProducer<String, String>(props);

        for(int i = 10; i < 20; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, "key-"+i, "value-"+i);
            producer.send(record);
            log.info("第{}条消息：{}发送完成！",i, "key-"+i);
        }
        producer.close();
    }
}
